#include <QDebug>
#include <QMessageBox>
#include <QThread>
#include "usbprinter.h"

UsbPrinter::UsbPrinter(QObject *parent)
    : PrinterClient{parent}
{}

UsbPrinter::~UsbPrinter() {
    disconnect();
    m_device.unload();
}

bool UsbPrinter::setPrinter(const QString &portName) {
    m_portName = portName;
    m_device.setFileName("e:\\TSCLIB.dll");

    if (!m_device.load()) {
        qDebug() << "TSCLIB.dll加载失败:" << m_device.errorString();
        QMessageBox::critical(nullptr, "错误", "无法加载打印机驱动库");
        return false;
    }

    // 解析函数
    openport = (TSCopenport)m_device.resolve("openport");
    sendcommand = (TSCsendcommand)m_device.resolve("sendcommand");
    closeport = (TSCcloseport)m_device.resolve("closeport");
    sendbinarydata = (TSCsendbinarydata)m_device.resolve("sendBinaryData");
    usbprinterquery = (TSCusbprinterquery)m_device.resolve("usbprinterquery");

    if (!openport || !sendcommand || !sendbinarydata || !closeport) {
        qDebug() << "无法解析DLL函数";
        QMessageBox::critical(nullptr, "错误", "打印机驱动库不兼容");
        m_device.unload();
        return false;
    }

    return true;
}

bool UsbPrinter::connect() {
    if (!openport || !sendcommand || !sendbinarydata || !closeport) {
        return false;
    }

    // 打开端口
    if (openport(m_portName.toLocal8Bit().data()) != 1) {
        qDebug() << "无法打开打印机端口";
        QMessageBox::critical(nullptr, "错误", "无法连接到打印机");
        emit errorOccurred(QString("无法连接到打印机"));
        m_device.unload();
        return false;
    }

    return true;
}

void UsbPrinter::disconnect() {
    // 关闭端口
    closeport();
}

void UsbPrinter::sendData(const QByteArray &command) {
    qDebug() << "开始打印";
    if (!connect()) {
        emit errorOccurred(QString("打印机连接失败。"));
        return;
    }
    // 发送打印指令

    int result = sendbinarydata(command.data(), command.count());
    if (result != 1) {
        qDebug() << "打印指令执行失败。";
        emit errorOccurred(QString("打印指令执行失败。"));
        disconnect();
        return;
    }

    disconnect();
    qDebug() << "打印完成";
}
